//实现对student表的增删改查操作
//增加记录

const Students = require("../models/Student");

//student: name age gender
async function createStudent(student) {
  let { name, age, gender } = student;
  const studentInstance = await Students.create({
    name,
    age,
    gender,
  });
  return {
    msg: "创建成功",
    data: studentInstance,
  };
}
//删除记录 得找到那条记录
async function deleteStudent(id) {
  let result = await queryStudent({
    id,
  });
  if (result.length > 0) {
    await result[0].destroy();
    return {
      msg: "删除成功",
    };
  } else {
    return {
      msg: "没有找到该学生",
    };
  }
}
//更新记录 得找到那条记录
async function updateStudent(id, student) {
  let result = await queryStudent({
    id,
  });
  if (result.length > 0) {
    result[0].name = student.name;
    result[0].age = student.age;
    result[0].gender = student.gender;
    await result[0].save();
    return {
      msg: "更新成功",
    };
  } else {
    return {
      msg: "没有找到该学生",
    };
  }
}
//查询记录
async function queryStudent(where) {
  let result = await Students.findAll({
    where,
  });
  return result;
}
//根据姓名来查询学生
async function queryStudentByName(name) {
  let where = {
    name,
  };
  let result = await Students.findOne({
    where,
  });
  if (result) {
    return {
      msg: "查询成功",
      data: result,
    };
  } else {
    return {
      msg: "没有找到该学生",
    };
  }
}
module.exports = {
  createStudent,
  deleteStudent,
  updateStudent,
  queryStudent,
  queryStudentByName,
};
